define(function (require) {
var zsApp = require('app');  
zsApp.controller('resourceClassifyCtrl', ['$rootScope', '$scope', '$http', '$timeout', 'cache', 'selectCache', 'promptCache', function($rootScope, $scope, $http, $timeout, cache, selectCache, promptCache) {

	$scope.isNext = false;
	$scope.next = false;
    $scope.hasSelected = false;

    $scope.edit_isNext = false;
    $scope.edit_next = false;
    $scope.edit_back = false;
    $scope.edit_hasSelected = false;

	// 添加资源
    var resCategoryId = [],     
		resId 		  = [];

	// 上级机构ID
    $scope.parentId = cache.get('parentId');
    // 上级资源分类名
    $scope.resName = cache.get('resName');
    
    // pagination
    $rootScope.paginationConf = { 
        currentPage    : 1,
        totalItems     : 10,
        itemsPerPage   : 10,
        pagesLength    : 15,
        perPageOptions : [20, 30, 40, 50, 100],
        onChange: function(){  
            var self = this,
                treeReqVo = {
                    id          : cache.get('resCategoryId')||0,
                    pageNumber  : self.currentPage,  
                    pageSize    : self.itemsPerPage,  
                };
            $http
            ({
                url    : $scope.zsUrl+'digitalhome-boss/product/resCategors/getSublevelInfo',
                method : 'POST',
                data   : treeReqVo,

            }).success(function(res) {  console.log(cache.get('resCategoryId'));

                if( res.result_code != '0000' ) {
                    $scope.isNoData = false;
                    return false;
                }
                    
                // 表格数据
                $scope.tabVal = res.result;
                // 遍历每条数据对应的ID
                angular.forEach(res.result, function(obj, i) {
                    $scope.dataID[i] = obj.resCategoryId;
                });
                // 总共有多少条数据
                self.totalItems = res.length;

            }).error(function(err) {
                $scope.isNoData = false;
            });

        }
    };

    // reload table
    $scope.reloadPagination = function() {
        $scope.paginationConf.onChange();
    };

    /******************************** 新增 ********************************/ 

    // 新增按钮（打开第一个弹窗）
    $scope.newlyAdded = function() {  
        superior();
        $scope.isNext = false;
        $scope.next = false;
        emptyVal('resName');
        emptyVal('categoryOrder');
        emptyVal('description');
    };

    // 新增并关闭（第一页）
    $scope.newlyAddedClose = function() {
    	newlyAddedData();
    };

    // 新增并添加资源（第二页）
    $scope.newlyAddedNextStep = function() {
    	$scope.isNext = true;
		$scope.next = true;
		newlyAddedData();
        $scope.newlyAddedResListTabVal = [];
    };

    // 新增（第一页）
    function newlyAddedData() {
    	
    	var newlyAddedData = {
            parentId         : cache.get('resCategoryId'),
        	resCategoryId    : '',
        	resName          : $scope.newlyAdded_resName||'',
        	categoryOrder    : $scope.newlyAdded_categoryOrder||'',
        	description      : $scope.newlyAdded_description||''          
        };

        $http
        ({
            url         : $scope.zsUrl+'digitalhome-boss/product/resCategors/addResCategors',
            method      : 'POST',
            data        : newlyAddedData,

        }).success(function(res) {

            if( res.result_code != '0000' ) {
                promptCache.errorPrompt(res.message);
                $scope.isNext = false;
                $scope.next = false;
                return false;
            }
            
            // 资源分类ID
            resCategoryId = [];
            resCategoryId.push(res.result);
            
            promptCache.successPrompt(res.message);
            reloadTable();
            
        }).error(function(err) {
            promptCache.errorPrompt('请求失败！');
            return false;
        });
    };

    // 添加资源 列表（第二页，弹窗）
	$scope.paginationResList = { 
        currentPage    : 1,
        totalItems     : 10,
        itemsPerPage   : 20,
        pagesLength    : 15,
        perPageOptions : [20, 50, 100, 200, 500, 1000],
        onChange: function(){ 
            
            var self = this,
    		resourcesVo = {
	    		resCategoryId 	: resCategoryId.toString()||0,
	    	    pageNumber  	: self.currentPage,  
                pageSize    	: self.itemsPerPage,  
                resName         : $scope.newlyAddedListSearch||'',
                resTypeId       : $scope.newlyAddedListSelect||'',
	    	};

            $http
            ({
                url    : $scope.zsUrl+'digitalhome-boss/product/resCategors/getResList',
                method : 'POST',
                data   : resourcesVo,

            }).success(function(res) {  console.log(res);

                if( res.result_code != '0000' ) {
                    $scope.isNoData = false;
                    return false;
                }

                // 页面加载时跳出函数
                if( !resCategoryId ) {
                    return false;
                }

                // 表格数据
                $scope.resListTabVal = res.result;

                // 总共有多少条数据
                self.totalItems = res.length;
                	
                $scope.addResource = function() {

                	$scope.resTypeList = [];
                    resId = [];
                    $scope.listBool = false;

	                angular.forEach(res.resourceTypeList, function(obj, i) {
	                	$scope.resTypeList[i] = { 'id' : obj.resTypeId, 'name' : obj.name }
	                });

                    // 重新加载
                    $scope.paginationResList.onChange();
                };
                
            }).error(function(err) {
                $scope.isNoData = false;
            });

        }
    };

    // 提交选择的resCategoryId、resId（第二页，弹窗）（新增、修改复用）
   	;(function() {

   		// 全选
        $scope._selectAll= function (bool, allObj) {  

    		resId = [];

            if(bool) {
            	angular.forEach(allObj, function(obj, i) {
            		resId[i] = obj.resId;
            	});
                $scope.hasSelected = true;
            }
            else {
            	resId 	      = [];
                $scope.hasSelected = false;
            }

            $scope.needResListId = { 'resCategoryId' : resCategoryId, 'resId' : resId };
            console.log($scope.needResListId);
        };

        //  单选（多选）
        $scope._select= function (bool, singleObj) {  

        	if(bool) {
        		resId.push(singleObj.resId);
        	}
        	else {
        		rmSame(resId, singleObj.resId);
        	}

            if(resId.length!=0){
                $scope.hasSelected = true;
            }
            else {
                $scope.hasSelected = false;
            }
        	
        	$scope.needResListId = { 'resCategoryId' : resCategoryId, 'resId' : resId };
        }; 

        // 移除相同元素
        function rmSame(arr, val) {
        	for(var i in arr) {
        		if(arr[i]==val) {
        			arr.splice(i,1);
        		}
        	}
        };
   	})();
        
    // 选中的资源列表（新增、修改复用）
    $scope.submitChoseList = function() { 

    	if(resId.length==0) {
    		promptCache.errorPrompt('请至少选中一条数据操作！');
    		return false;
    	}

    	$http
    	({
    		url 	: $rootScope.zsUrl+'digitalhome-boss/product/resCategors/batchAddRes',
    		method	: 'POST',
    		data 	: $scope.needResListId,

    	}).success(function(res) { console.log(res);

            $scope.paginationSelectedResList.onChange();

    	}).error(function(err) { console.log(err);
             
    	});
    };

    // 加载选中的列表（第二页）（新增、修改复用）
    $scope.paginationSelectedResList = { 
        currentPage    : 1,
        totalItems     : 10,
        itemsPerPage   : 20,
        pagesLength    : 15,
        perPageOptions : [20, 50, 100, 200, 500, 1000],
        onChange: function(){ 
            
            var self = this,
            treeReqVo = {
                id              : resCategoryId.toString(),
                pageNumber      : self.currentPage,  
                pageSize        : self.itemsPerPage,  
            };

            $http
            ({
                url    : $scope.zsUrl+'digitalhome-boss/product/resCategors/getResRelationList',
                method : 'POST',
                data   : treeReqVo,

            }).success(function(res) {  console.log(res);

                if( res.result_code != '0000' ) {
                    $scope.isNoData = false;
                    return false;
                }

                // 页面加载时跳出函数
                if( !resCategoryId ) {
                    return false;
                }

                // 表格数据
                $scope.newlyAddedResListTabVal = res.result;
                $scope.editResListTabVal = res.result;
                
                // 总共有多少条数据
                self.totalItems = res.length;
                
            }).error(function(err) {
                $scope.isNoData = false;
            });

        }
    };

    // 删除（新增、修改复用）
    $scope.deleteRes = function(i, val) { 
        
        var needResListId = { resCategoryId : val.resCategoryId, resId : val.resId };

        console.error(needResListId);

        $http
        ({
            url     : $scope.zsUrl+'digitalhome-boss/product/resCategors/deleteResByResId',
            method : 'POST',
            data   : needResListId,

        }).success(function(res) {  

            $scope.paginationSelectedResList.onChange();

        }).error(function(err) {
            promptCache.errorPrompt('请求失败！');
            return false;
        });
    };

    // 检索（第二页，弹窗）（新增、修改复用）
    ;(function() {
        // 资源分类（下拉框）
        $scope.getSelectId = function() {
            // console.log($scope.newlyAddedListSelect);
        };

        // 检索（搜索框）
        $scope.searchBtn = function() {
            // console.log($scope.newlyAddedListSearch);
            $scope.paginationResList.onChange();
        };
    })();


    /******************************** 详情 ********************************/ 

    // 详情
    var detailsId = 0;
    $scope.details = function(i) { 
        
        superior();

        detailsId = $scope.dataID[i];

        $http
        ({
            url     : $scope.zsUrl+'digitalhome-boss/product/resCategors/getResCategors/'+$scope.dataID[i],
            method  : 'GET',

        }).success(function(res) {  console.log(res);

            if( res.result_code != '0000' ) {
                return false;
            }

            $scope.details_resName          = res.result.resName;
            $scope.details_categoryOrder    = res.result.categoryOrder;
            $scope.details_description      = res.result.description;  
        }).error(function(err) {
            promptCache.errorPrompt('请求失败！');
            return false;
        });  

        $scope.paginationDetails.onChange(detailsId);       
    };

    $scope.paginationDetails = { 
        currentPage    : 1,
        totalItems     : 10,
        itemsPerPage   : 20,
        pagesLength    : 15,
        perPageOptions : [20, 50, 100, 200, 500, 1000],
        onChange: function(dataID){ 
            
            var self = this,
                resourcesVo = {
                    id              : detailsId,
                    pageNumber      : self.currentPage,  
                    pageSize        : self.itemsPerPage,
                };

            $http
            ({
                url    : $scope.zsUrl+'digitalhome-boss/product/resCategors/getResRelationList',
                method : 'POST',
                data   : resourcesVo,

            }).success(function(res) {  console.log(res);

                if( res.result_code != '0000' ) {
                    $scope.isNoData = false;
                    return false;
                }

                // 页面加载时跳出函数
                if( !detailsId ) {
                    return false;
                }
                    
                // 表格数据
                $scope.detailsTabList = res.result;

                // 总共有多少条数据
                self.totalItems = res.length;
                
            }).error(function(err) {
                $scope.isNoData = false;
            });

        }
    };


    /******************************** 修改 ********************************/ 

    // 修改按钮（打开第一个弹窗，并展示详情）
    $scope.edit = function(i) {

        superior();

        $scope.edit_isNext = false;
        $scope.edit_next = false;
        $scope.edit_back = false;

        $scope.index = i;
        $http
        ({
            url     : $scope.zsUrl+'digitalhome-boss/product/resCategors/getResCategors/'+$scope.dataID[i],
            method  : 'GET',

        }).success(function(res) {  console.log(res);

            if( res.result_code != '0000' ) {
                return false;
            }

            resCategoryId = [];
            resCategoryId.push(res.result.resCategoryId);

            $scope.edit_parentId         = res.result.parentId;
            $scope.edit_resName          = res.result.resName;
            $scope.edit_categoryOrder    = res.result.categoryOrder;
            $scope.edit_description      = res.result.description;

        }).error(function(err) {
            promptCache.errorPrompt('请求失败！');
            return false;
        });
    };

    // 修改并添加资源（第二页）
    $scope.editNextStep = function() {
        $scope.edit_isNext = true;
        $scope.edit_next = true;
        $scope.edit_back = true;
        editData();
        $scope.paginationEdit.onChange();
    };

    // 返回第一页（第一页）
    $scope.editBack = function() {
        $scope.edit_isNext = false;
        $scope.edit_next = false;
        $scope.edit_back = false;
    };

    // 修改（第一页）
    function editData() {
        var editData = {
            parentId                : $scope.edit_parentId||'',
            resCategoryId           : $scope.dataID[$scope.index]||'',
            resName                 : $scope.edit_resName||'',
            categoryOrder           : $scope.edit_categoryOrder,
            description             : $scope.edit_description||''          
        }

        $http
        ({
            url     : $scope.zsUrl+'digitalhome-boss/product/resCategors/modify',
            method  : 'POST',
            data    : editData,

        }).success(function(res) {

            if( res.result_code != '0000' ) {
                promptCache.errorPrompt(res.message);
                return false;
            }

            promptCache.successPrompt(res.message);
            reloadTable();

        }).error(function(err) {
            promptCache.errorPrompt('修改失败！');
        });
    };

    // 修改（第二页，展示详情）
    $scope.paginationEdit = { 
        currentPage    : 1,
        totalItems     : 10,
        itemsPerPage   : 20,
        pagesLength    : 15,
        perPageOptions : [20, 50, 100, 200, 500, 1000],
        onChange: function(dataID){ 
            
            var self = this,
                resourcesVo = {
                    id              : $scope.dataID[$scope.index]||0,
                    pageNumber      : self.currentPage,  
                    pageSize        : self.itemsPerPage,
                };

            $http
            ({
                url    : $scope.zsUrl+'digitalhome-boss/product/resCategors/getResRelationList',
                method : 'POST',
                data   : resourcesVo,

            }).success(function(res) {  // console.log(res);

                if( res.result_code != '0000' ) {
                    $scope.isNoData = false;
                    return false;
                }
                    
                // 表格数据
                $scope.editResListTabVal = res.result;

                // 总共有多少条数据
                self.totalItems = res.length;
                
            }).error(function(err) {
                $scope.isNoData = false;
            });

        }
    };




    // 删除
    $scope.getDataID = function() {
        // data length
        var len = $scope.dataID.length;
        // param id
        var whichId = 'resCategoryId';
        // param
        var deleteUrl = 'product/resCategors/delete';
        // enable disabled
        // var isEnableUrl = 'product/resCategors/modifyStatus';

        // multiple selections 
        $scope.selectAll= function (bool, obj) {
            selectCache.selectAll(bool, $scope.dataID);
        };

        //  Single or multiple selections 
        $scope.select= function (selectObj, bool) {   
            var selectId = selectObj.resCategoryId;        
            selectCache.select(selectId, bool, len);    
        }; 

        // check
        $scope.check= function () {
            selectCache.check();
        };

        // delete
        $scope.delete= function () { 
            selectCache.delete(whichId, deleteUrl);
            reloadTable();
        };
    };

    // superior
    function superior() {
        if( cache.get('resName') ) {
            $scope.resName = cache.get('resName');
        }else {
            $scope.resName = '最上级';
        }
    };

    // reload table
    function reloadTable() {
        $timeout(function() {
            $scope.paginationConf.onChange();
            $scope.master = false;
        },1500);
    };

    // empty input
    function emptyVal(val) {
        var emptyVal = document.getElementById(val);
        emptyVal.value = '';
    }     
}])
.directive('resourceclassifyNewlyadded', function() {
	return {
		restrict	: 'E',
		templateUrl : 'product/resourceClassify/newlyAdded.html',
		replace		: true,	
	}
})
.directive('resourceclassifyDetails', function() {
	return {
		restrict	: 'E',
		templateUrl	: 'product/resourceClassify/details.html',
		replace		: true,	
	}
})
.directive('resourceclassifyEdit', function() {
	return {
		restrict	: 'E',
		templateUrl	: 'product/resourceClassify/edit.html',
		replace		: true,	
	}
})
.directive('resourceclassifyDelete', function() {
	return {
		restrict	: 'E',
		templateUrl	: 'product/resourceClassify/delete.html',
		replace		: true,	
	}
})
.directive('resourceclassifyTable', function() {
    return {
        restrict    : 'E',
        templateUrl : 'product/resourceClassify/table.html',
        replace     : true, 
    }
})
.directive('resourceclassifyNewlyaddedlist', function() {
    return {
        restrict    : 'E',
        templateUrl : 'product/resourceClassify/newlyAdded-list.html',
        replace     : true, 
    }
})
.directive('resourceclassifyEditlist', function() {
    return {
        restrict    : 'E',
        templateUrl : 'product/resourceClassify/edit-list.html',
        replace     : true, 
    }
})
.directive('resourceclassifyAddedlist', function() {
    return {
        restrict    : 'E',
        templateUrl : 'product/resourceClassify/add-list.html',
        replace     : true, 
    }
})
});